using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace OA.UI
{
    /// <summary>
    /// 权限验证
    /// </summary>
    public class ValidateAuthority : ActionFilterAttribute
    {
        private string menuCode;
        private string buttonCode;

        /// <summary>
        /// 验证菜单权限
        /// </summary>
        public ValidateAuthority(string menuCode)
        {
            this.menuCode = menuCode;
        }

        /// <summary>
        /// 验证按钮权限
        /// </summary>
        public ValidateAuthority(string menuCode, string buttonCode)
        {
            this.menuCode = menuCode;
            this.buttonCode = buttonCode;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Result = LoginValidateAttribute.ValidLogin(filterContext.HttpContext);
            if (filterContext.Result == null)
            {
                var context = filterContext.RequestContext.HttpContext;
                var ret = new BLL.Authority().ValidateAuthority(string.IsNullOrEmpty(buttonCode) ? Common.EnumType.ResourceType.Menu : Common.EnumType.ResourceType.Button, Common.Keys.WebSiteCode, menuCode, buttonCode, BLL.LoginUser.LoginManager.UserName);
                if (ret.success == false)
                {
                    if (context.Request.IsAjaxRequest() == false)
                    {
                        filterContext.Result = UI.Utils.ErrorPage("访问失败", "对不起，您的权限不足！");
                    }
                    else
                    {
                        filterContext.Result = new ContentResult() { Content = Newtonsoft.Json.JsonConvert.SerializeObject(ret) };
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
}